package com.ctvit.framework.web.upload;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ctvit.common.StringTrans;
import com.ctvit.sms.platform.service.ContentLogService;
import com.ctvit.wsservice.basedata.domain.ZppmTProginfo;
import net.sf.json.JSONObject;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.ctvit.framework.web.context.ContextHolder;
import org.apache.commons.lang3.StringUtils;

/**
 * @author lindasen
 *         文件上传
 */
public class FileUpLoadedServlet extends HttpServlet {

	// 定义文件的上传路径
	private String uploadPath = "";
	//文件重复重命名时 查找括号内数字的patten
	private String regex = "\\([0-9]+?\\)$";
	private Pattern pattern = Pattern.compile(regex);
	//返回的json
	private HashMap TFBJson;

	// 限制文件的上传大小
	public static int maxPostSize = 1 * 1024 * 1024;     //1M
	// 可以上传的文件后缀名
	private static String[] allowableExtened = new String[]{"jpg"};
	//可上传文件大小的MB、KB显示
	public static String maxPostSize_String;

	static {
		maxPostSize_String = StringTrans.bytes2kb(maxPostSize);
	}

	public static char SUCCESS = '1';
	public static char ERROR = '0';
	public static char ALERT = '2';

	ContentLogService contentService = ContextHolder.getBean(ContentLogService.class);

	/**
	 * 实例业务service,处理上传前后的事件
	 *
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void processRequest(HttpServletRequest request,
	                           HttpServletResponse response) throws ServletException, IOException {
		TFBJson = new HashMap();

		String str_progCode = request.getHeader("progCode"); //节目代码
		String str_chanlZoneId = request.getHeader("chanlZoneId"); //专区节目单主键

		if (StringUtils.isEmpty(str_progCode)) {
			setTFBContent(ERROR, "节目代码不能为空", null);
			returnJson(response);
			return;
		} else if (StringUtils.isEmpty(str_chanlZoneId)) {
			setTFBContent(ERROR, "专区节目单主键不能为空", null);
			returnJson(response);
			return;
		}

		uploadPath = getServletContext().getRealPath("/") + "mam4ch5" + File.separator;
//		System.out.println(uploadPath);
		try {
			String filePath = this.doUpLoad(request, str_progCode, uploadPath);
		} catch (ServletException e) {
			returnJson(response);
			return;
		}

		//update zppm_t_proginfo z_preview_exists
		ZppmTProginfo zppmTProginfo = new ZppmTProginfo();
		zppmTProginfo.setZProcode(str_progCode);
		zppmTProginfo.setZPreviewExists("X");
		try {
			//TODO  现在只按节目代码进行了更新，没有添加音频字幕等条件
			contentService.updateProgPreview(str_chanlZoneId, zppmTProginfo, new String[]{"zPreviewExists"});
		} catch (Exception e) {
			setTFBContent(ERROR, "数据库更新失败，请稍后再试。", null);
			returnJson(response);
			return;
		}

		setTFBContent(SUCCESS, "上传成功", null);
		returnJson(response);
		return;
	}

//	/**
//	 * 插入t_attach表
//	 *
//	 * @param fileName
//	 * @param fileExtend
//	 * @param objectTable
//	 * @param objectKey
//	 */
//	private Long doRecordFile(String fileName, String fileExtend, String objectTable, String objectKey) {
//		int lastNo = customMsgService.getLastAttachNo(objectTable, objectKey);
//		int attachNo = lastNo + 1;
//
//		Attach attach = customMsgService.insertAttach(fileName, fileExtend, objectTable, objectKey, Long.valueOf(attachNo));
//		return attach.getAttachNo();
//	}

//	/**
//	 * 将文件移动到remote服务器
//	 *
//	 * @param filename
//	 * @param meetingPk
//	 */
//	private void toRemote(String filename, Long meetingPk) {
//		String fileNameEncode = "";
//		try {
//			fileNameEncode = URLEncoder.encode(filename, "utf8");
//			fileNameEncode = fileNameEncode.replaceAll("\\+", "%20");
//		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
//		}
//		String urlString = domainUrl;
////						urlString="http://localhost:8080/messageCenter/attached/";
//		FileTransfer.httpTranster(urlString + meetingPk.toString() + "/" + fileNameEncode, filename, meetingPk.toString(), "1");
//	}

	/**
	 * 文件上传过程
	 *
	 * @param request
	 * @param progCode
	 * @param path
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	private String doUpLoad(HttpServletRequest request,
	                        String progCode, String path) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");

		// 设置最多只允许在内存中存储的数据,单位:字节
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(4096);
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setSizeMax(maxPostSize);              // byte
		String itemName = "";
		String fileName = "";
		String fileExtend = "";
		try {
			List fileItems = upload.parseRequest(request);
			Iterator iter = fileItems.iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (!item.isFormField()) {
					itemName = item.getName();                  //先存一下完整的 用来分成 文件名和后缀
					fileName = itemName.substring(0, itemName.lastIndexOf("."));
					fileExtend = itemName.substring(itemName.lastIndexOf(".") + 1).toLowerCase();
					itemName = progCode.toUpperCase() + ".jpg";     //文件名按： 节目代码 保存

					if (validFileExtend(fileExtend) == false) {    //看看扩展名是不是允许上传
						setTFBContent(ERROR, "不支持所上传的文件类型", null);
						throw new ServletException("不支持所上传的文件类型");
					}
					try {
						//先看看文件目录是否存在
						File fileDir = new File(path);
						if (!fileDir.exists()) {
							fileDir.mkdirs();
						}
						File uploadFile = new File(path + itemName);
						//看看文件是否存在了
//						while (uploadFile.exists() == true) {      //存在的话 就文件名结尾添加"(1)'
////								fileName = getRename(fileName);
//							itemName = fileName + "." + fileExtend;
//							uploadFile = new File(path + itemName);
//						}
						item.write(uploadFile);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		return path + itemName;

	}

//	/**
//	 * 当文件已经存在，需要在文件名后面加上"(1)"  括号里的数字会累加
//	 *
//	 * @param fileName
//	 * @return
//	 */
//	private String getRename(String fileName) {
//		int reNameIndex = 0;
//		Matcher matcher = pattern.matcher(fileName);
//		while (matcher.find()) {
//			String renameMatched = matcher.group(0);
//			renameMatched = renameMatched.replace("(", "");
//			renameMatched = renameMatched.replace(")", "");
//			reNameIndex = Integer.valueOf(renameMatched);
//
//			fileName = fileName.replaceAll(regex, "");      //删除以前的后缀 下面重新加入
//		}
//		reNameIndex = reNameIndex + 1;
//		fileName = fileName + "(" + reNameIndex + ")";
//		return fileName;
//	}

	/**
	 * 检验扩展名是否支持上传
	 *
	 * @param fileExtend
	 * @return
	 */
	private boolean validFileExtend(String fileExtend) {
		return StringTrans.contains(allowableExtened, fileExtend.toLowerCase());
	}

	/**
	 * 根据request获取上下文的域名
	 * http://localhost:8080/messageCenter
	 *
	 * @param request
	 * @return
	 */
	public String getRequestURL(HttpServletRequest request) {
		StringBuffer url = request.getRequestURL();
		String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length())
				.append(request.getContextPath()).toString();
		return tempContextUrl;
	}

	private void returnJson(HttpServletResponse response) {
		if (TFBJson == null) {
			TFBJson = new HashMap();
		}
		returnJson(response, TFBJson);
	}

	private void returnJson(HttpServletResponse response, HashMap map) {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
//		String jsonStr = "{\"name\":\"fly\",\"type\":\"虫子\"}";
		JSONObject json = JSONObject.fromObject(map);
		String jsonStr = json.toString();
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.write(jsonStr);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

	/**
	 * 设置返回的TFB的json
	 *
	 * @param state
	 * @param message
	 * @param content
	 */
	private void setTFBContent(char state, Object message, Object content) {
		TFBJson = new HashMap();
		TFBJson.put("success", state);
		TFBJson.put("message", message);
		TFBJson.put("content", content);
	}

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.processRequest(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.processRequest(req, resp);
	}

}
